package dev.guide.net;

import java.io.File;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import dev.guide.R;

public class MulThreadDownloader extends Activity {
	private EditText pathText;
	private ProgressBar progressBar;
	private TextView resultView;
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			if (!Thread.currentThread().isInterrupted()) {
				switch (msg.what) {
				case 1:
					int size = msg.getData().getInt("size");
					progressBar.setProgress(size);
					int result = (int) (((float) size / (float) progressBar
							.getMax()) * 100);
					resultView.setText(result + "%");
					if (progressBar.getMax() == size) {
						Toast.makeText(MulThreadDownloader.this,
								"Download finished.", Toast.LENGTH_LONG).show();
					}
					break;
				case -1:
					String error = msg.getData().getString("error");
					Toast.makeText(MulThreadDownloader.this, error,
							Toast.LENGTH_LONG).show();
					break;
				}
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.download);
		pathText = (EditText) this.findViewById(R.id.path);
		progressBar = (ProgressBar) findViewById(R.id.downloadbar);
		resultView = (TextView) findViewById(R.id.resultView);
		Button button = (Button) findViewById(R.id.download);
		button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				String path = pathText.getText().toString();
				if (Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {
					download(path, Environment.getExternalStorageDirectory());
				} else {
					Toast.makeText(MulThreadDownloader.this,
							"No SDcard error!", Toast.LENGTH_LONG).show();
				}
			}
		});
	}

	public void download(final String path, final File saveDir) {
		new Thread(new Runnable() {
			public void run() {
				FileDownloader downer = new FileDownloader(
						MulThreadDownloader.this, path, saveDir, 3);

				progressBar.setMax(downer.getFileSize());// 设置进度条的最大刻度
				try {
					downer.download(new DownloadProgressListener() {
						public void onDownloadSize(int size) {
							Message msg = new Message();
							msg.what = 1;
							msg.getData().putInt("size", size);
							handler.sendMessage(msg);// 发送消息
						}
					});
				} catch (Exception e) {
					Message msg = new Message();
					msg.what = -1;
					msg.getData().putString("error", "下载失败");
					handler.sendMessage(msg);
				}
			}
		}).start();
	}
}
